<?php
namespace App\V3\Api\Controllers;
use Illuminate\Http\Request;
use App\V3\Api\Services\ImageLabelService;
use App\Http\Controllers\Api\BaseController;
use Illuminate\Support\Facades\Validator;
use OSS\OssClient;
use App\V3\Api\Models\AdminAddendumModel;
use Illuminate\Support\Facades\DB;
class ImageLabelController extends BaseController
{
    protected $ossClient;
    public function __construct(Request $request){
        parent::__construct($request);
        $this->ossClient=new OssClient(
            config('app.aliyun_oss_key'),
            config('app.aliyun_oss_secret'),
            config('app.aliyun_oss_endpoint')
            );
    }

    /**
     * 添加图片画册标签
     * @param is_top     置顶
     * @param label_name 标签名称
     * @param sort_number 排序数字
     */
    public function addImageLabel(Request $request){

        $validator = Validator::make(
            $data  = $request->all(), [
                'pa_id' =>'required'
            ],[
                'pa_id.required' => '画册的id,不能为空!'
            ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {

            return response()->json(['code' => 1,'msg' => $info,'data' => '']);
        }
     if(!empty($data['is_top']) && $data['is_top']==1){
            
            $condition['is_top']       = 1;
            $condition['pa_id']        = $data['pa_id'];
            $condition['user_id']      = $this->getUserId();
            $condition['main_id']      = $this->getMainUserId();
    
    
            $info = ImageLabelService::getImageLabelInfo($condition);
    
            if(!empty($info)){
    
                ImageLabelService::updImageLabel($condition, ['is_top'=>0]);
            }
        }
        $data['create_time']  = time();
        $data['user_id']      = $this->getUserId();
        $data['main_id']      = $this->getMainUserId();
        $data['is_top']       = empty($data['is_top'])?0:$data['is_top'];
        $data['sort_number']  = empty($data['sort_number'])?'':$data['sort_number'];
        $data['label_name']   = empty($data['label_name'])?'':$data['label_name'];

        $id = ImageLabelService::addImageLabel($data);

        if(!empty($id)){

            return response()->json(['code'=>0,'msg'=>'success','data'=>['label_id'=>$id]]);

        }else{

            return response()->json(['code'=>1,'msg'=>'保存失败','data'=>'']);
        }

    }

    /**
     * 查询图片画册标签列表
     *
     * @param curr_page   当前页
     * @param page_size   显示个数
     * @param pa_id       文字画册id
     * @param sort_number 排序数字
     */
    public function getImageLabelList(Request $request){

        $currentPage = !empty($request->input('curr_page'))?$request->input('curr_page'):1;
        $pageSize    = !empty($request->input('page_size'))?$request->input('page_size'):20;

        //$condition['user_id'] = $this->getUserId();
        $condition['pa_id']   = $request->input('pa_id');
        $sort_number          = !empty($request->input('sort_number'))?$request->input('sort_number'):'';

        $list  = ImageLabelService::getImageLabelList($condition,$sort_number,$currentPage,$pageSize);
        /*  echo "<pre>";
         var_dump($list);die; */
        if(!empty($list['data'])){

           foreach ($list['data'] as $ik=>$iv){

               if(!empty($iv['Album_imgs'])){


                   $imgArr = explode(',',$iv['Album_imgs']);

                   foreach ($imgArr as $iak=>$iav){

                       $imgArr[$iak]=SELF::addWatermark($this->ossClient,$iav,$this->getMainUserId());
                   }
                   $list['data'][$ik]['Album_imgs'] = $imgArr;

               }
                   $list['data'][$ik]['create_time']=date('Y-m-d H:i:s',$iv['create_time']);
                   $list['data'][$ik]['update_time']=date('Y-m-d H:i:s',$iv['update_time']);
           }
        }

        return response()->json(['code'=>0,'msg'=>'success','data'=>$list]);
    }

    /**
     * 修改内容标签
     *
     * @param label_id    内容标签id
     * @param label_name  标签名称
     * @param is_top      置顶
     * @param sort_number 排序数字
     */
    public function updImageLabel(Request $request){

        if(empty($ctId = $request->input('label_id'))){

            return response()->json(['code'=>1,'msg'=>'内容标签id,不能为空','data'=>'']);
        }

        $condition['id'] = $ctId;
        //$condition['user_id'] = $this->getUserId();

        $updData = $request->all();
        $updData['update_time']  = time();

        if(isset($updData['Album_imgs'])){

            unset($updData['Album_imgs']);
        }

         $updCondition['is_top']  = 1;
         $updCondition['pa_id']   = $request->input('pa_id');
         $updCondition['user_id'] = $this->getUserId();

        $info = ImageLabelService::getImageLabelInfo($updCondition);

        if(!empty($info)){

            if(isset($updData['is_top'])){

                if($updData['is_top'] == 1){

                    ImageLabelService::updImageLabel($updCondition,['is_top'=> 0]);
                }
            }
        }

        unset($updData['label_id']);unset($condition['is_top']);

        $bool = ImageLabelService::updImageLabel($condition,$updData);

        if($bool){

            return response()->json(['code'=>0,'msg'=>'修改成功','data'=>'']);
        }

        return response()->json(['code'=>1,'msg'=>'修改失败','data'=>'']);

    }

    /**
     * 删除内容标签
     * @param label_id 内容标签id
     */
    public function delImageLabel(Request $request){

        if(empty($ctId = $request->input('label_id'))){

            return response()->json(['code'=>1,'msg'=>'内容标签id,不能为空','data'=>'']);
        }

        $condition['id'] = $ctId;
        //$condition['user_id'] = $this->getUserId();

        $info = ImageLabelService::getImageLabelInfo($condition);

        if(empty($info)){

            return response()->json(['code'=>1,'msg'=>'内容标签，不存在！','data'=>'']);
        }

        $bool = ImageLabelService::delImageLabel($condition);

        if($bool){

            if(!empty($info['Album_imgs'])){

            $info['Album_imgs'] = explode(',',$info['Album_imgs']);

                    foreach ($info['Album_imgs'] as $k=>$v){

                        if(empty($v)){
                            //删除OSS里的文件
                            $delOssRes=SELF::delOssFilePath($v, $this->ossClient, $this->getMainUserId());
                            if(!empty($delOssRes)) return $this->fail('',$delOssRes);
                        }
                    }
            }

            return response()->json(['code'=>0,'msg'=>'删除成功','data'=>'']);
        }

        return response()->json(['code'=>1,'msg'=>'删除失败','data'=>'']);

    }

    /**
     * 添加水印
     * @param unknown $file
     */
    static public function addWatermark($client,$file,$mainId){
        if(empty($file)) return $file;
        $adminInfo = AdminAddendumModel::select('clear_watermark_or_not')->where(['main_id'=>$mainId])->first();

        if($adminInfo['clear_watermark_or_not']==1){

            return $file;
        }else{
                $delPath = strstr($file, 'uploads/');
                $imgInfo = $client->getObjectMeta(config('app.aliyun_oss_bucket'), $delPath);
                if(strpos($imgInfo['content-type'],'image/') !== false){

                    return $file = $file.config('app.aliyun_oss_img_watermark');
                }
            }
            return $file;
    }

    /**
     * 删除oss里的文件
     * @param unknown $file
     * @param unknown $mainId
     */
    static public function delOssFilePath($file,$client,$mainId){
        if(empty($file)) return $file;
            DB::beginTransaction();
            try {
                $delPath = strstr($file, 'uploads/');
                $imgInfo=$client->getObjectMeta(config('app.aliyun_oss_bucket'), $delPath);
                AdminAddendumModel::where(['main_id'=>$mainId])
                ->decrement('file_total_size', $imgInfo['content-length']);
                $client -> deleteObject(config('app.aliyun_oss_bucket'), $delPath);
                DB::commit();
            } catch (\Exception $e) {
                DB::rollBack(); 
                return "";
            }
    }


}
